#include "CheckersBoard.h"
#include "CheckersApp.h"

const DirectX::XMFLOAT3 CheckersBoard::BLACK_COLOR = DirectX::XMFLOAT3(0.4f, 0.0f, 0.0f);
const DirectX::XMFLOAT3 CheckersBoard::WHITE_COLOR = DirectX::XMFLOAT3(1.0f, 0.94f, 0.96f);

CheckersBoard::CheckersBoard(CheckersApp *app):
	app(app)
{
	memset(highlight, -1, sizeof(highlight));
	ZeroMemory(highlightColors, sizeof(highlightColors));
}

CheckersBoard::~CheckersBoard()
{
}

void CheckersBoard::Draw()
{
	// Configure input assembler
	ID3D11Buffer *vertexBuffers[] = {app->VBBlock()};
	UINT stride = sizeof(CheckersApp::Vertex), offset = 0;
	app->D3DDeviceContext()->IASetIndexBuffer(app->IBBlock(), DXGI_FORMAT_R16_UINT, 0);
	app->D3DDeviceContext()->IASetInputLayout(app->InputLayout());
	app->D3DDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	app->D3DDeviceContext()->IASetVertexBuffers(0, 1, vertexBuffers, &stride, &offset);

	// Configure shaders
	ID3D11Buffer *cbPerObject = app->CBPerObject();
	app->D3DDeviceContext()->PSSetShader(app->PSColor(), NULL, 0);
	app->D3DDeviceContext()->PSSetConstantBuffers(0, 1, &cbPerObject);
	app->D3DDeviceContext()->VSSetShader(app->VSColor(), NULL, 0);
	app->D3DDeviceContext()->VSSetConstantBuffers(0, 1, &cbPerObject);

	// Compute world-view-proj matrix
	DirectX::XMMATRIX wvpMatrix = DirectX::XMMatrixMultiply(
		worldMatrix,
		app->ViewProjMatrix());

	// Draw all 64 squares of the checkerboard
	for (int i = 0; i < 8; ++i)
	{
		float z = -3.5f + 1.0f*i;

		for (int j = 0; j < 8; ++j)
		{
			float x = -3.5f + 1.0f*j;

			// Set shader parameters
			CheckersApp::ObjectParams objParams;

			objParams.g_worldViewProj = DirectX::XMMatrixMultiplyTranspose(
				DirectX::XMMatrixTranslation(x, 0.0f, z),
				wvpMatrix);

			int highlightIndex = highlight[i][j];
			if (highlightIndex == -1) // Default checkerboard color
				objParams.g_color = (i+j) % 2 ? WHITE_COLOR : BLACK_COLOR;
			else // Custom color
				objParams.g_color = highlightColors[highlightIndex];

			app->D3DDeviceContext()->UpdateSubresource(cbPerObject, 0, NULL, &objParams, 0, 0);

			// Draw the box
			app->D3DDeviceContext()->DrawIndexed(36, 0, 0);
		}
	}
}